
package com.epam.video.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpProtocolParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * TODO: add description
 * 
 * @author slava
 */
public class HttpUtils {
  private static final int DEFAULT_BUFFER_SIZE = 65536;

  public static String executeRequest(final String url) {
    String responseResult = null;
    try {
      HttpResponse response = executeGetHttpRequest(url);
      responseResult = responseToString(response);
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Throwable e) {
      e.printStackTrace();
    }
    return responseResult;
  }

  private static HttpClient newHttpClientInstance() {
    HttpClient client = new DefaultHttpClient();
    HttpProtocolParams.setContentCharset(client.getParams(), "UTF-8");
    return client;
  }

  private static HttpResponse executeGetHttpRequest(final String url) throws ClientProtocolException, IOException {
    final HttpClient client = newHttpClientInstance();
    HttpUriRequest request = new HttpGet(url);
    return client.execute(request);
  }

  private static final String responseToString(final HttpResponse response) throws IOException {
    final HttpEntity entity = response.getEntity();
    final InputStream in = entity.getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(in), DEFAULT_BUFFER_SIZE);
    final StringBuilder builder = new StringBuilder();
    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
      builder.append(line);
    }
    return builder.toString();
  }
}
